package com.zuma.test;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

// 当key为fb9b3857531e0d89时
// 应当将18812341234加密为da2e9df28673165000312dfb15f57517
// 并能成功解密出来

/**
 * AES加密器
 * 
 */
public class AESEncryptor {

	//密码
	private static final String key = "fb9b3857531e0d89";
	//iv偏移量
	private static final String iv = "0000000000000000";


	//加密
	public static String encrypt(String encryptStr) {
		try {
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
			SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

			byte[] encrypted = cipher.doFinal(encryptStr.getBytes());

			return byte2HexStr(encrypted);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}

	//解密
	public static String decrypt(String encryptedStr) {
		try {
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
			SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);

			byte[] bytes = hexStr2Bytes(encryptedStr);
			byte[] original = cipher.doFinal(bytes);

			return new String(original);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}


	//十六进制转字符串转byte[]
	public static byte[] hexStr2Bytes(String hexStr) {
		hexStr = hexStr.trim().replace(" ", "").toUpperCase(Locale.US);
		int m = 0, n = 0;
		int iLen = hexStr.length() / 2; //计算长度
		byte[] ret = new byte[iLen]; //分配存储空间

		for (int i = 0; i < iLen; i++) {
			m = i * 2 + 1;
			n = m + 1;
			ret[i] = (byte) (Integer.decode("0x" + hexStr.substring(i * 2, m) + hexStr.substring(m, n)) & 0xFF);
		}
		return ret;
	}

	//byte[]转字符串
	public static String byte2HexStr(byte[] bytes) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < bytes.length; n++) {
			stmp = (Integer.toHexString(bytes[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs;
	}


}